#!/usr/bin/env bash

# For each virtual machine where tests run, this script performs the following:
# - starts VM
# - starts the test suite witin a VM
# - stops the VM after the test suite is done

# global variable for script exit value
export EXIT_VALUE=0

register_failing_specs() {
	EXIT_VALUE=1
}

run_vagrant() {
	local box="$1"
	vagrant up "$box"
}

# Halt vagrant after tests are done running, unless KEEP_RUNNING environment
# variable is set to 'true'.
stop_vagrant() {
	local box="$1"
	if [ -z "$KEEP_RUNNING" ]; then
		vagrant halt "$box"
	else
		echo
		echo "KEEP_RUNNING is set. Vagrant not halted."
	fi
}

run_tests() {
	local box="$1"
	local test_file="/vagrant/test/run-tests-within-vm"
	echo "Running test suite on $box from: $test_file"
	echo
	vagrant ssh "$box" -c "cd /vagrant; $test_file"
}

exit_message() {
	local exit_val="$1"
	echo
	if [ $exit_val == 0 ]; then
		echo "Success, tests pass!"
	else
		echo "Tests failed!" 1>&2
	fi
}

run_tests_on_vm() {
	local vm="$1"
	run_vagrant "$vm"
	run_tests "$vm"
	local tests_exit_value="$?"
	stop_vagrant "$vm"
	if [ $tests_exit_value -gt 0 ]; then
		register_failing_specs
	fi
}

main() {
	run_tests_on_vm "ubuntu_two_five"

	exit_message "$EXIT_VALUE"
	exit "$EXIT_VALUE"
}
main
